import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useXunfeiAIStore = defineStore('xunfeiAI', () => {
  // AI助手状态
  const isOpen = ref(false)
  const isMinimized = ref(false)
  
  // 消息历史
  const messages = ref([
    { 
      text: '👟 欢迎来到鞋城！我是您的专属AI购物助手，可以帮您找鞋、推荐款式、查询尺码和库存，有什么可以帮助您的吗？', 
      isUser: false,
      time: new Date().toLocaleTimeString()
    }
  ])
  
  // 加载状态
  const isLoading = ref(false)
  
  // 讯飞AI配置
  const xunfeiConfig = ref({
    appId: 'ec6704db',
    apiKey: '97702f6fa3bec78354cea4d12946f63a',
    apiSecret: 'M2E5NGI2MzFhNDUzZGRjOTcyOWUzZjk0',
    apiPassword: 'rFanHQUBkEOUbZnjUOoB:tzOSJAWvogCYsgkbXkcW',
    userId: '10284711用户'
  })
  
  // 计算属性
  const hasConfig = computed(() => {
    return !!(
      xunfeiConfig.value.appId && 
      xunfeiConfig.value.apiKey && 
      xunfeiConfig.value.apiSecret
    )
  })
  
  const messageCount = computed(() => messages.value.length)
  
  // 方法
  const toggleAI = () => {
    isOpen.value = !isOpen.value
  }
  
  const openAI = () => {
    isOpen.value = true
  }
  
  const closeAI = () => {
    isOpen.value = false
  }
  

  
  const addMessage = (message) => {
    messages.value.push({
      ...message,
      time: new Date().toLocaleTimeString()
    })
  }
  
  const clearMessages = () => {
    messages.value = [
      { 
        text: '👟 欢迎来到鞋城！我是您的专属AI购物助手，可以帮您找鞋、推荐款式、查询尺码和库存，有什么可以帮助您的吗？', 
        isUser: false,
        time: new Date().toLocaleTimeString()
      }
    ]
  }
  
  const updateConfig = (config) => {
    xunfeiConfig.value = { ...xunfeiConfig.value, ...config }
  }
  
  const initialize = () => {
    // 从localStorage恢复状态
    const savedState = localStorage.getItem('xunfei-ai-state')
    if (savedState) {
      try {
        const state = JSON.parse(savedState)
        if (state.messages) {
          messages.value = state.messages
        }
        if (state.config) {
          xunfeiConfig.value = { ...xunfeiConfig.value, ...state.config }
        }
      } catch (error) {
        console.warn('恢复AI助手状态失败:', error)
      }
    }
  }
  
  // 保存状态到localStorage
  const saveState = () => {
    const state = {
      messages: messages.value,
      config: xunfeiConfig.value,
      timestamp: Date.now()
    }
    localStorage.setItem('xunfei-ai-state', JSON.stringify(state))
  }
  
  // 监听状态变化并保存
  const setupAutoSave = () => {
    // 监听消息变化
    const unwatchMessages = ref.watch(messages, () => {
      saveState()
    }, { deep: true })
    
    // 监听配置变化
    const unwatchConfig = ref.watch(xunfeiConfig, () => {
      saveState()
    }, { deep: true })
    
    return () => {
      unwatchMessages()
      unwatchConfig()
    }
  }
  
  return {
    // 状态
    isOpen,
    messages,
    isLoading,
    xunfeiConfig,
    
    // 计算属性
    hasConfig,
    messageCount,
    
    // 方法
    toggleAI,
    openAI,
    closeAI,
    addMessage,
    clearMessages,
    updateConfig,
    initialize,
    saveState,
    setupAutoSave
  }
}, {
  persist: {
    key: 'xunfei-ai-store',
    storage: localStorage,
    paths: ['messages', 'xunfeiConfig']
  }
})